package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.review

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaReviewBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.feedback.FeedbackGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.review.subview.IReviewGhanaNewUserDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.review.subview.IReviewGhanaOldUserDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.review.subview.ReviewGhanaNewUserDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.review.subview.ReviewGhanaOldUserDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabrepay.TabRepayGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util.AppReviewUtil
import org.json.JSONObject

class ReviewGhanaActivity : AppCompatActivity() {

    private lateinit var reviewViewModel: ReviewGhanaViewModel
    private lateinit var binding: ActivityGhanaReviewBinding
    private lateinit var adapter: ReviewGhanaPageAdapter
    private lateinit var boldDialog: ReviewGhanaNewUserDialog
    private lateinit var normalDialog: ReviewGhanaOldUserDialog

    @SuppressLint("NotifyDataSetChanged", "ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        reviewViewModel = ViewModelProvider(this)[ReviewGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaReviewBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val list = binding.list
        val refresh = binding.refresh

        // 初始化下拉刷新
        refresh.apply {
            setColorSchemeColors(Color.parseColor("#5277D6"))

            setOnRefreshListener { reviewViewModel.pageDetail() }
        }

        // 初始化adapter
        adapter = ReviewGhanaPageAdapter(emptyList())
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 初始化dialog
        boldDialog = ReviewGhanaNewUserDialog(object : IReviewGhanaNewUserDialogListener {
            override fun onClick(star: Int) {
                handleReviewStar(star)
            }
        })
        normalDialog = ReviewGhanaOldUserDialog(object : IReviewGhanaOldUserDialogListener {
            override fun onClick(star: Int) {
                handleReviewStar(star)
            }
        })

        // 页面loading状态接口监听
        reviewViewModel.loadingResult.observe(this@ReviewGhanaActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                refresh.isRefreshing = false
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        reviewViewModel.pageDetailResult.observe(this@ReviewGhanaActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.success != null) {
                binding.loanAmount.text = pageDetailResult.success.optString("amountFormat")
                binding.loanTerm.text = pageDetailResult.success.optString("daysFormat")
            }
        })

        // 评价接口监听
        reviewViewModel.reviewDialogResult.observe(this@ReviewGhanaActivity, Observer {
            val reviewDialogResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (reviewDialogResult.error != null) {
                showMessage(reviewDialogResult.error)
            }
            if (reviewDialogResult.boldDialog != null) {
                boldDialog.setDialogContent(reviewDialogResult.boldDialog)
                boldDialog.showNow(supportFragmentManager, "ReviewDialog")

            } else if (reviewDialogResult.normalDialog != null) {
                normalDialog.setDialogContent(reviewDialogResult.normalDialog)
                normalDialog.showNow(supportFragmentManager, "ReviewDialog")
            }
        })

        // 卡列表接口监听
        reviewViewModel.walletResult.observe(this@ReviewGhanaActivity, Observer {
            val walletResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (walletResult.error != null) {
                showMessage(walletResult.error)
            }
            if (walletResult.success != null) {
                binding.walletName.text = walletResult.success.optString("walletType")
                binding.walletMobile.text = walletResult.success.optString("walletMobile")

                val logo = walletResult.success.optString("walletLogo")
                if (logo.startsWith("http")) {
                    Glide.with(this).load(logo).into(binding.walletLogo)
                }
            }
        })

        // 推荐产品列表接口监听
        reviewViewModel.commendProductsResult.observe(this@ReviewGhanaActivity, Observer {
            val commendProductsResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (commendProductsResult.error != null) {
                // TODO: 失败
                showMessage(commendProductsResult.error)
            }
            if (commendProductsResult.success != null) {
                // TODO: 成功
                adapter.dataList = commendProductsResult.success
                adapter.notifyDataSetChanged()
                if (commendProductsResult.success.isEmpty()) {
                    binding.recommendBg.visibility = View.GONE
                } else {
                    binding.recommendBg.visibility = View.VISIBLE
                }
            }
        })

        // 点击申请
        back.setOnClickListener {
            startNextActivity(TabRepayGhanaActivity::class.java)
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 查询页面详情
        reviewViewModel.pageDetail()

        // 查询产品列表
        reviewViewModel.commendProducts()

        // 查询评价框配置
        reviewViewModel.reviewDialog()
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }

    fun toPlayStore() {
        val intent =
            Intent(Intent.ACTION_VIEW, Uri.parse(ProjectApplication.mPlayStore)).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
        if (intent.resolveActivity(ProjectApplication.instance.packageManager) != null) {
            ProjectApplication.instance.startActivity(intent)
        } else {
            ProjectApplication.instance.startActivity(
                Intent.createChooser(intent, "Please select a browser to open")
            )
        }
    }

    fun handleReviewStar(star: Int) {
        Handler(Looper.getMainLooper()).postDelayed({
            if (star < 4) {
                val intent = Intent(this@ReviewGhanaActivity, FeedbackGhanaActivity::class.java)
                startActivity(intent)
            } else {
                AppReviewUtil.launchReviewFlow(this@ReviewGhanaActivity) {
                    if (!it) {
                        toPlayStore()
                    }
                }
            }
        }, 800)
    }
}

class ReviewGhanaPageAdapter(
    var dataList: List<JSONObject>
) :
    RecyclerView.Adapter<ReviewGhanaPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_disbursing_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val icon: ImageView = view.findViewById(R.id.icon)
        private val name: TextView = view.findViewById(R.id.name)
        private val amount: TextView = view.findViewById(R.id.amount)
        private val star: TextView = view.findViewById(R.id.star)
        private val download: TextView = view.findViewById(R.id.download)
        private val installBg: LinearLayout = view.findViewById(R.id.installBg)

        fun bindData(item: JSONObject) {
            val product = item.optString("product")
            name.text = item.optString("appName")
            amount.text = item.optString("appLoanAmount")
            star.text = item.optString("star")
            download.text = item.optString("download")

            val logo = item.optString("appLogo")
            if (logo.isNotBlank()) {
                icon.visibility = View.VISIBLE
                Glide.with(icon).load(logo).into(icon)
            } else {
                icon.visibility = View.GONE
            }

            val link = item.optString("appLink")
            installBg.setOnClickListener {
                if (link.isNotBlank()) {
                    installBg.context.hitPoint("DC_INSTALL_CLICK", product)

                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    }
                    if (intent.resolveActivity(ProjectApplication.instance.packageManager) != null) {
                        ProjectApplication.instance.startActivity(intent)
                    } else {
                        ProjectApplication.instance.startActivity(
                            Intent.createChooser(intent, "Please select a browser to open")
                        )
                    }
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}

fun Context.startNextActivity(
    activity: Class<out AppCompatActivity>? = null,
    params: HashMap<String, String> = HashMap()
) {
    val nextActivity = activity ?: return
    try {
        val intent = Intent(this, nextActivity)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        params.keys.forEach { gKey ->
            intent.putExtra(gKey, params[gKey])
        }
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

